/**
 * Copyright (c) 2024 Huawei Technologies Co., Ltd.
 * This file is a part of the CANN Open Software.
 * Licensed under CANN Open Software License Agreement Version 1.0 (the "License").
 * Please refer to the License for details. You may not use this file except in compliance with the License.
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
 * See LICENSE in the root of the software repository for the full text of the License.
 */

#include "../../../common/data_utils.h"
#ifndef ASCENDC_CPU_DEBUG
#include "acl/acl.h"
extern void sort_custom_do(uint32_t blockDim, void *l2ctrl, void *stream, uint8_t *srcGmValue, uint8_t *srcGmIndex, 
    uint8_t *dstGmValue, uint8_t *dstGmIndex, uint8_t *workspace, uint8_t *tiling);
#else
#include "tikicpulib.h"
extern "C" __global__ __aicore__ void sort_custom(GM_ADDR srcGmValue, GM_ADDR srcGmIndex, GM_ADDR dstGmValue,
                            GM_ADDR dstGmIndex, GM_ADDR workspace, GM_ADDR tiling);
#endif
constexpr uint8_t BLOCK_DIM = 1;
constexpr uint32_t TILINGDATA_SIZE = 1;
constexpr uint32_t WORKSPACE_SIZE = 16*1024*1024;
constexpr uint8_t ELEMENTCOUNT = 128;

extern uint8_t *GenerateTiling(uint32_t elementCount);

static bool CompareResult(const void *outputData, int64_t outSize, std::string goldenName)
{
    void *goldenData;
#ifdef ASCENDC_CPU_DEBUG
    goldenData = (uint8_t *)AscendC::GmAlloc(outSize);
#else
    CHECK_ACL(aclrtMallocHost((void **)(&goldenData), outSize));
#endif
    size_t goldenSize = outSize;
    bool ret = ReadFile("../output/golden_" + goldenName + ".bin", goldenSize, goldenData, goldenSize);
    if (ret) {
        printf("ReadFile golden_%s.bin success!\n", goldenName.c_str());
    } else {
        printf("test failed!\n");
        return false;
    }
    constexpr float EPS = 1e-4;
    int64_t wrongNum = 0;

    for (int i = 0; i < outSize / sizeof(float); i++) {
        float a = (reinterpret_cast<const float *>(outputData))[i];
        float b = (reinterpret_cast<const float *>(goldenData))[i];
        float ae = std::abs(a - b);
        float re = ae / abs(b);
        if (ae > EPS && re > EPS) {
            printf("CompareResult golden_%s.bin failed output is %lf, golden is %lf\n", goldenName.c_str(), a, b);
            wrongNum++;
        }
    }
#ifdef ASCENDC_CPU_DEBUG
    AscendC::GmFree((void *)goldenData);
#else
    CHECK_ACL(aclrtFreeHost(goldenData));
#endif
    if (wrongNum != 0) {
        return false;
    } else {
        printf("CompareResult golden_%s.bin success!\n", goldenName.c_str());
        return true;
    }
}

int32_t main(int32_t argc, char *argv[])
{
    uint32_t blockDim = BLOCK_DIM;
    size_t inputSize_srcGmValue = ELEMENTCOUNT * sizeof(float);
    size_t inputSize_srcGmIndex = ELEMENTCOUNT * sizeof(uint32_t);
    size_t outputSize_dstGmValue = ELEMENTCOUNT * sizeof(float);
    size_t outputSize_dstGmIndex = ELEMENTCOUNT * sizeof(uint32_t);

    size_t workspaceSize = WORKSPACE_SIZE;
    size_t tilingFileSize = TILINGDATA_SIZE * sizeof(uint32_t);

#ifdef ASCENDC_CPU_DEBUG
    uint8_t *srcGmValue = (uint8_t *)AscendC::GmAlloc(inputSize_srcGmValue);
    uint8_t *srcGmIndex = (uint8_t *)AscendC::GmAlloc(inputSize_srcGmIndex);
    uint8_t *dstGmValue = (uint8_t *)AscendC::GmAlloc(outputSize_dstGmValue);
    uint8_t *dstGmIndex = (uint8_t *)AscendC::GmAlloc(outputSize_dstGmIndex);

    uint8_t *workspace = (uint8_t *)AscendC::GmAlloc(workspaceSize);
    uint8_t *tiling = (uint8_t *)AscendC::GmAlloc(tilingFileSize);

    ReadFile("../input/input_srcGmValue.bin", inputSize_srcGmValue, srcGmValue, inputSize_srcGmValue);
    ReadFile("../input/input_srcGmIndex.bin", inputSize_srcGmIndex, srcGmIndex, inputSize_srcGmIndex);

    memcpy_s(tiling, tilingFileSize, GenerateTiling(ELEMENTCOUNT), tilingFileSize);

    AscendC::SetKernelMode(KernelMode::AIV_MODE);
    ICPU_RUN_KF(sort_custom, blockDim, srcGmValue, srcGmIndex, dstGmValue, dstGmIndex, workspace, tiling);
 
    WriteFile("../output/output_dstGmValue.bin", dstGmValue, outputSize_dstGmValue);
    WriteFile("../output/output_dstGmIndex.bin", dstGmIndex, outputSize_dstGmIndex);

    bool goldenResult = true;
    goldenResult = CompareResult(dstGmValue, outputSize_dstGmValue, "dstGmValue");
    if (goldenResult) {
        printf("test pass!\n");
    } else {
        printf("test failed!\n");
    }

    AscendC::GmFree((void *)srcGmValue);
    AscendC::GmFree((void *)srcGmIndex);
    AscendC::GmFree((void *)dstGmValue);
    AscendC::GmFree((void *)dstGmIndex);
    AscendC::GmFree((void *)workspace);
    AscendC::GmFree((void *)tiling);

#else
    CHECK_ACL(aclInit(nullptr));
    aclrtContext context;
    int32_t deviceId = 0;
    CHECK_ACL(aclrtSetDevice(deviceId));
    CHECK_ACL(aclrtCreateContext(&context, deviceId));
    aclrtStream stream = nullptr;
    CHECK_ACL(aclrtCreateStream(&stream));

    uint8_t *srcGmValueHost, *srcGmIndexHost, *dstGmValueHost, *dstGmIndexHost, *workspaceHost;
    uint8_t *srcGmValueDevice, *srcGmIndexDevice, *dstGmValueDevice, 
        *dstGmIndexDevice, *workspaceDevice, *tilingDevice;
    
    CHECK_ACL(aclrtMallocHost((void **)(&srcGmValueHost), inputSize_srcGmValue));
    CHECK_ACL(aclrtMallocHost((void **)(&srcGmIndexHost), inputSize_srcGmIndex));
    CHECK_ACL(aclrtMallocHost((void **)(&dstGmValueHost), outputSize_dstGmValue));
    CHECK_ACL(aclrtMallocHost((void **)(&dstGmIndexHost), outputSize_dstGmIndex));
    CHECK_ACL(aclrtMallocHost((void **)(&workspaceHost), workspaceSize));

    CHECK_ACL(aclrtMalloc((void **)&srcGmValueDevice, inputSize_srcGmValue, ACL_MEM_MALLOC_HUGE_FIRST));
    CHECK_ACL(aclrtMalloc((void **)&srcGmIndexDevice, inputSize_srcGmIndex, ACL_MEM_MALLOC_HUGE_FIRST));
    CHECK_ACL(aclrtMalloc((void **)&dstGmValueDevice, outputSize_dstGmValue, ACL_MEM_MALLOC_HUGE_FIRST));
    CHECK_ACL(aclrtMalloc((void **)&dstGmIndexDevice, outputSize_dstGmIndex, ACL_MEM_MALLOC_HUGE_FIRST));
    CHECK_ACL(aclrtMalloc((void **)&workspaceDevice, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST));
    CHECK_ACL(aclrtMalloc((void **)&tilingDevice, tilingFileSize, ACL_MEM_MALLOC_HUGE_FIRST));

    ReadFile("../input/input_srcGmValue.bin", inputSize_srcGmValue, srcGmValueHost, inputSize_srcGmValue);
    ReadFile("../input/input_srcGmIndex.bin", inputSize_srcGmIndex, srcGmIndexHost, inputSize_srcGmIndex);

    CHECK_ACL(aclrtMemcpy(workspaceDevice, workspaceSize, workspaceHost, workspaceSize, ACL_MEMCPY_HOST_TO_DEVICE));
    CHECK_ACL(aclrtMemcpy(tilingDevice, tilingFileSize, GenerateTiling(ELEMENTCOUNT),
        tilingFileSize, ACL_MEMCPY_HOST_TO_DEVICE));

    CHECK_ACL(aclrtMemcpy(srcGmValueDevice, inputSize_srcGmValue, srcGmValueHost, inputSize_srcGmValue, 
        ACL_MEMCPY_HOST_TO_DEVICE));
    CHECK_ACL(aclrtMemcpy(srcGmIndexDevice, inputSize_srcGmIndex, srcGmIndexHost, inputSize_srcGmIndex, 
        ACL_MEMCPY_HOST_TO_DEVICE));

    sort_custom_do(blockDim, nullptr, stream, srcGmValueDevice, srcGmIndexDevice, dstGmValueDevice,
        dstGmIndexDevice, workspaceDevice, tilingDevice);

    CHECK_ACL(aclrtSynchronizeStream(stream));
    
    CHECK_ACL(aclrtMemcpy(dstGmValueHost, outputSize_dstGmValue, dstGmValueDevice, outputSize_dstGmValue, 
        ACL_MEMCPY_DEVICE_TO_HOST));
    CHECK_ACL(aclrtMemcpy(dstGmIndexHost, outputSize_dstGmIndex, dstGmIndexDevice, outputSize_dstGmIndex, 
        ACL_MEMCPY_DEVICE_TO_HOST));

    WriteFile("../output/output_dstGmValue.bin", dstGmValueHost, outputSize_dstGmValue);
    WriteFile("../output/output_dstGmIndex.bin", dstGmIndexHost, outputSize_dstGmIndex);

    bool goldenResult = true;
    goldenResult = CompareResult(dstGmValueHost, outputSize_dstGmValue, "dstGmValue");
    if (goldenResult) {
        printf("test pass!\n");
    } else {
        printf("test failed!\n");
    }

    CHECK_ACL(aclrtFree(srcGmValueDevice));
    CHECK_ACL(aclrtFree(srcGmIndexDevice));
    CHECK_ACL(aclrtFree(dstGmValueDevice));
    CHECK_ACL(aclrtFree(dstGmIndexDevice));
    CHECK_ACL(aclrtFree(workspaceDevice));
    CHECK_ACL(aclrtFree(tilingDevice));

    CHECK_ACL(aclrtFreeHost(srcGmValueHost));
    CHECK_ACL(aclrtFreeHost(srcGmIndexHost));
    CHECK_ACL(aclrtFreeHost(dstGmValueHost));
    CHECK_ACL(aclrtFreeHost(dstGmIndexHost));
    CHECK_ACL(aclrtFreeHost(workspaceHost));

    CHECK_ACL(aclrtDestroyStream(stream));
    CHECK_ACL(aclrtDestroyContext(context));
    CHECK_ACL(aclrtResetDevice(deviceId));
    CHECK_ACL(aclFinalize());
#endif
    return 0;
}
